import { useEffect, useState, useRef } from "react";
import { useSearchParams } from "react-router-dom";
import BpmnModeler from "bpmn-js/lib/Modeler";
import { get,revoke } from "@/api/instance";
import { resolve } from "@/api/task";
import {jwtDecode} from "jwt-decode";
import { message } from "antd";
import { useNavigate } from "react-router-dom";
import style from "./detail.module.scss";
import {Button} from "antd";
import Modal from "antd/es/modal/Modal.js";
import {getToken} from "@/utils/token.js";

function Resolve() {
  const divEl = useRef(null);
  const [searchParams] = useSearchParams();
  const [id] = useState(searchParams.get("id"));
  const [instanceId] = useState(searchParams.get("processInstanceId"))
  const navigate = useNavigate();
  const [currentUserInfoId, setCurrentUserInfoId] = useState(-1);
  const [processStartUserId] = useState(searchParams.get("startUserId"));

  useEffect(() => {
    getProcessXmlById();
    decode(getToken())
  }, []);

  const getProcessXmlById = () => {
    get(instanceId).then((result) => {
      if (result.code === 200) {
        let resultData = result.data;
        initModeler(resultData.processXmlDto.bpmnXml,resultData.tasks);
      }
    });
  };


  const decode = (token) => {
    const decodedToken = jwtDecode(token);
    if(decodedToken) {
      setCurrentUserInfoId(decodedToken.user_info_id)
    }

  };



  const initModeler = (xml,nodes) => {
    divEl.current.innerHTML = "";
    const modeler = new BpmnModeler({
      container: divEl.current,
      height: 240,
      additionalModules: [
          {
              paletteProvider: ["value", ''], //禁用/清空左侧工具栏
            labelEditingProvider: ["value", ''], //禁用节点编辑
              contextPadProvider: ["value", ''], //禁用图形菜单
              bendpoints: ["value", {}], //禁用连线拖动
              zoomScroll: ["value", ''], //禁用滚动
              moveCanvas: ['value', ''], //禁用拖动整个流程图
              move: ['value', ''] //禁用单个图形拖动
          }
      ]
    });
    modeler.importXML(xml, (err) => {
      if (err) {
        message.error("流程图加载失败")
      } else {
        if(nodes && nodes.length > 0) {
          const elementRegistry = modeler.get('elementRegistry');
          console.log(elementRegistry)
          const modeling = modeler.get('modeling');
          nodes.forEach(node => {
            if(node.status === 'complete') {
              modeling.setColor(elementRegistry.get(node.taskDefKey), {
                fill: 'green', // 填充颜色
                stroke: 'black' // 边框颜色
              });
            }
            if(node.status === 'current') {
              modeling.setColor(elementRegistry.get(node.taskDefKey), {
                fill: 'yellow', // 填充颜色
                stroke: 'black' // 边框颜色
              });
            }
          })
        }
      }
    });
  };




  const handleClick = (type) => {
    let input = {
      taskId: id,
      commandType: type
    }
    resolve(input).then((res) => {
      if (res.code === 200) {
        message.info("处理成功").then(r => console.log(r));
        navigate(-1);
      }
    })
  };


  const handRevoke = () => {
    revoke(instanceId).then((res) => {
      if (res.code === 200) {
        message.info("撤回成功").then(r => console.log(r));
        navigate(-1);
      }
    })
  }



  return (
    <>
      <div className={style.container}>
        <div className={style.btns}>
          <Button type={"primary"} onClick={() => handleClick('COMPLETE')}>同意</Button>
          <Button type={"primary"} onClick={() => handleClick()}>传阅</Button>
          <Button type={"primary"} onClick={() => handleClick()}>审批历史</Button>
          <Button type={"primary"} onClick={() => handleClick()}>转办</Button>
          <Button type={"primary"} onClick={() =>
          Modal.confirm({
            title: '确认撤回吗？',
            content: '撤回后，流程将回到最初的审批结点',
            onOk() {
              handleClick('RECALL');
            },
            onCancel() {
              console.log('Cancel');
            },
          })
          }>撤回</Button>
          {
            currentUserInfoId == processStartUserId  ?  <Button type={"primary"} onClick={() => handRevoke()}>撤销</Button> : ''
          }
          <Button type={"primary"} onClick={() => handleClick()}>打印</Button>
          <Button type={"primary"} onClick={() => handleClick()}>超管终止</Button>
        </div>
        <div className={style.diagram} ref={divEl}></div>

        {/* <Button type="primary" onClick={handleClick}>
          发起流程
        </Button> */}
      </div>
    </>
  );
}

export default Resolve;
